﻿namespace ElencySolutions.ImageMap.Properties
{
    using System;
    using System.Web.UI;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;
    using EPiServer;
    using EPiServer.Core;
    using EPiServer.SpecializedProperties;
    using EPiServer.UI.WebControls;
    using EPiServer.Web.PropertyControls;
    using EPiServer.Core.PropertySettings;

    [PropertySettings(typeof(ImageMapPropertySettings), true)]
    public class ImageMapPropertyControl : PropertyDataControl
    {

        #region Members

        private PropertyDataCollection _propertyDataCollection;

        public const int DEFAULT_POPUP_WIDTH = 745;
        public const int DEFAULT_POPUP_HEIGHT = 600;

        private PropertyUrlControl _imageUrl;
        private TextBox _imageWidth;
        private TextBox _imageHeight;
        private TextBox _imageAltText;
        private TextBox _defaultLinkUrl;
        private DropDownList _target;
        private HiddenField _xmlValue;
        private Panel _formPlaceHolder;

        #endregion Members

        #region Properties

        #endregion Properties

        #region Event handlers


        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Init"/> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs"/> object that contains the event data.</param>
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            Initialise();
        }

        #endregion Event handlers

        private ImageMapPropertySettings GetSettings()
        {
            if (PropertyData.SettingsContainer != null)
            {
                PropertySettingsWrapper settingsWrapper = PropertyData.SettingsContainer.GetSetting(typeof(ImageMapPropertySettings));

                if (settingsWrapper != null)
                {
                    ImageMapPropertySettings settings = settingsWrapper.PropertySettings as ImageMapPropertySettings;

                    if (settings != null)
                        return settings;
                }
            }

            return null;
        }

        /// <summary>
        /// Initialises the control.
        /// </summary>
        private void Initialise()
        {
            if (PropertyData == null)
                return;

            _propertyDataCollection = new PropertyDataCollection();
        }

        /// <summary>
        /// Creates the edit controls.
        /// </summary>
        public override void CreateEditControls()
        {
            _formPlaceHolder = new Panel();
            _formPlaceHolder.Style.Add("margin-bottom", "5px");
            Controls.Add(_formPlaceHolder);

            Table table = new Table { CellSpacing = 0, CssClass = "epi-formLayout", ID = "LayoutTable" };
            table.Style["display"] = "block";
            table.Style["margin-bottom"] = "5px";
            _formPlaceHolder.Controls.Add(table);

            ImageMap imageMap = GetEntityData();

            _propertyDataCollection.Add(PropertyData.Name + "ImageUrl", new PropertyImageUrl());
            PropertyData propertyData = _propertyDataCollection[PropertyData.Name + "ImageUrl"];
            propertyData.Value = imageMap.ImageUrl;

            if (propertyData.Value != null)
            {
                try
                {
                    propertyData.ParseToSelf(propertyData.Value.ToString());
                }
                catch
                {
                    propertyData.Value = imageMap.ImageUrl;
                }
            }

            //propertyData.IsRequired = attribute.Required;

            IPropertyControl propertyControl = PropertyControlClassFactory.Instance.CreatePropertyControl(_propertyDataCollection[PropertyData.Name + "ImageUrl"]);
            _imageUrl = propertyControl as PropertyUrlControl;
            _imageUrl.ID = PropertyData.Name + "ImageUrl";
            _imageUrl.PropertyData = propertyData;
            _imageUrl.Properties = _propertyDataCollection;
            AddEditingRow(table, LanguageHelper.Translate("/elencySolutionsImageMap/imageUrl"), false, _imageUrl);
            _imageUrl.RenderType = RenderType.Edit;
            _imageUrl.SetupControl();
            
            _imageHeight = new TextBox { Text = imageMap.ImageHeight.ToString(), ID = "ImageHeight", MaxLength = 4 };
            AddEditingRow(table, LanguageHelper.Translate("/elencySolutionsImageMap/imageHeight"), false, _imageHeight);

            _imageWidth = new TextBox { Text = imageMap.ImageWidth.ToString(), ID = "ImageWidth", MaxLength = 4 };
            AddEditingRow(table, LanguageHelper.Translate("/elencySolutionsImageMap/imageWidth"), false, _imageWidth);

            _imageAltText = new TextBox { Text = imageMap.ImageAltText, ID = "ImageAltText" };
            AddEditingRow(table, LanguageHelper.Translate("/elencySolutionsImageMap/imageAltText"), false, _imageAltText);

            _defaultLinkUrl = new TextBox { Text = imageMap.DefaultLinkUrl, ID = "DefaultLinkUrl" };
            AddEditingRow(table, LanguageHelper.Translate("/elencySolutionsImageMap/defaultLinkUrl"), false, _defaultLinkUrl);

            _target = new DropDownList { ID = "Target" };
            _target.Items.Add(new ListItem(LanguageHelper.Translate("/elencySolutionsImageMap/sameWindow"), "_self"));
            _target.Items.Add(new ListItem(LanguageHelper.Translate("/elencySolutionsImageMap/newWindow"), "_blank"));

            ListItem listItem = _target.Items.FindByValue(imageMap.Target);

            if (listItem != null)
                listItem.Selected = true;

            AddEditingRow(table, LanguageHelper.Translate("/elencySolutionsImageMap/defaultLinkTarget"), false, _target);

            string xml = ImageMapHelper.SerializeObject(imageMap.Areas);
            xml = xml.Replace("ElencySolutions.ImageMap.Properties", "ElencySolutions.ImageMap");
            _xmlValue = new HiddenField { ID = "XmlValue", Value = xml };
            _formPlaceHolder.Controls.Add(_xmlValue);

            ImageMapPropertySettings settings = GetSettings();
            int popupHeight = settings != null && settings.PopupHeight.HasValue ? settings.PopupHeight.Value : DEFAULT_POPUP_HEIGHT;
            int popupWidth = settings != null && settings.PopupWidth.HasValue ? settings.PopupWidth.Value : DEFAULT_POPUP_WIDTH;

            ToolButton button = new ToolButton { ID = "EditImageMap", SkinID = "Edit", Text = LanguageHelper.Translate("/elencySolutionsImageMap/editImageMap") };
            _formPlaceHolder.Controls.Add(button);
            button.OnClientClick = string.Format("javascript:window.open('{0}?ImageUrl=' + escape(document.getElementById('{1}_ctl00').value) + '&Width=' + document.getElementById('{2}').value + '&Height=' + document.getElementById('{3}').value + '&Alt=' + escape(document.getElementById('{4}').value) + '&DefaultLinkUrl=' + escape(document.getElementById('{9}').value) + '&XmlValueId={5}&id={6}', 'ImageMapEditor', 'menubar=no,resizable=yes,scrollbars=no,status=no,toolbar=no,location=no,height={7},width={8}');return false;",
                    "/Util/ElencySolutions.ImageMapEditor.aspx",
                    _imageUrl.ClientID,
                    _imageWidth.ClientID,
                    _imageHeight.ClientID,
                    _imageAltText.ClientID,
                    _xmlValue.ClientID,
                    PageReference.StartPage.ID,
                    popupHeight,
                    popupWidth,
                    _defaultLinkUrl.ClientID);

            foreach (PropertyData currentPropertyData in _propertyDataCollection)
                currentPropertyData.InitializeData(CurrentPage.Property);
        }

        /// <summary>
        /// Creates the default controls.
        /// </summary>
        public override void CreateDefaultControls()
        {
            if (RenderType == RenderType.Default)
                Controls.Add(new Literal { Text = GetEntityData().GetHtml() });
            else
                base.CreateDefaultControls();
        }

        /// <summary>
        /// Adds the editing row.
        /// </summary>
        /// <param name="container">The container.</param>
        /// <param name="labelText">The label text.</param>
        /// <param name="required">if set to <c>true</c> [required].</param>
        /// <param name="controls">The controls.</param>
        private void AddEditingRow(Table container, string labelText, bool required, params Control[] controls)
        {
            // add row panel
            TableRow tableRow = new TableRow();
            container.Rows.Add(tableRow);

            // add label text
            TableHeaderCell headerCell = new TableHeaderCell { CssClass = "EP-tableCaptionCell" };

            HtmlGenericControl label = new HtmlGenericControl("span") { InnerText = labelText };

            if (required)
            {
                HtmlGenericControl asterix = new HtmlGenericControl("span") { InnerText = "*" };
                asterix.Style["margin-left"] = "3px";
                label.Controls.Add(asterix);
            }

            headerCell.Controls.Add(label);
            tableRow.Cells.Add(headerCell);

            // add control
            TableCell cell = new TableCell();
            cell.Style["padding-bottom"] = "0.3em";
            tableRow.Cells.Add(cell);

            foreach (Control control in controls)
                cell.Controls.Add(control);
        }

        private int StringToInt(string value)
        {
            int parsedValue;
            int.TryParse(value, out parsedValue);
            return parsedValue;
        }

        /// <summary>
        /// Applies edit changes
        /// </summary>
        public override void ApplyEditChanges()
        {
            ImageMap imageMap = GetEntityData();

            ((IPropertyControl)_imageUrl).ApplyChanges();

            imageMap.ImageUrl = _propertyDataCollection[0].Value != null ? _propertyDataCollection[0].Value.ToString() : string.Empty;
            imageMap.ImageAltText = _imageAltText.Text;
            imageMap.ImageHeight = StringToInt(_imageHeight.Text);
            imageMap.ImageWidth = StringToInt(_imageWidth.Text);
            imageMap.DefaultLinkUrl = _defaultLinkUrl.Text;
            imageMap.Target = _target.SelectedItem.Value;

            string xml = Page.Server.HtmlDecode(_xmlValue.Value).Replace("ElencySolutions.ImageMap", "ElencySolutions.ImageMap.Properties");
            Areas areas = ImageMapHelper.DeserializeObject<Areas>(xml);
            imageMap.Areas.Clear();
            imageMap.Areas.AddRange(areas);

            xml = ImageMapHelper.SerializeObject(imageMap);

            SetValue(xml);
        }


        /// <summary>
        /// Gets the string value for the property
        /// </summary>
        /// <returns>Property value as a string</returns>
        private string GetRawValue()
        {
            return PropertyData.Value == null ? string.Empty : PropertyData.Value.ToString();
        }

        /// <summary>
        /// Gets the typed entity data
        /// </summary>
        /// <returns>Entity data</returns>
        private ImageMap GetEntityData()
        {
            string xml = GetRawValue();

            if (string.IsNullOrEmpty(xml))
                return new ImageMap();

            try
            {
                return ImageMapHelper.DeserializeObject<ImageMap>(xml);
            }
            catch (Exception)
            {
                return new ImageMap();
            }
        }

    }
}
